package com.java.example.network

import com.java.example.network.response.BaseResponse
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable

/**
 * @author chenll
 * @date 2024/2/22
 */
class BaseObserver<T>(private val mCallBack: ICallBack<T>) : Observer<BaseResponse<T>> {
    override fun onSubscribe(d: Disposable) {
        mCallBack.onStart(d)
    }

    override fun onNext(tResponse: BaseResponse<T>) {
        try {
            if (tResponse.isSuccess()) {
                mCallBack.onResponse(tResponse.data)
            } else {
                mCallBack.onFail(tResponse, null)
            }
        } catch (throwable: Throwable) {
            onError(throwable)
        }
    }

    override fun onError(e: Throwable) {
        e.printStackTrace()
        mCallBack.onFail(null, e)
        mCallBack.onEnd()
    }

    override fun onComplete() {
        mCallBack.onEnd()
    }
}
